package org.jackysoft.service.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.jackysoft.entity.Variable;
import org.jackysoft.service.AbstractIdentifiedIntegerService;
import org.jackysoft.service.VariableService;
import org.joda.time.DateTime;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class VariableServiceImpl 
extends AbstractIdentifiedIntegerService<Variable>
implements VariableService {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5743404103295815240L;

	
	public VariableServiceImpl() {
	    this.type = Variable.class;
	}

	@Override
	public Variable get(Long entityId, String name)
			throws DataAccessException {
		Session session =getSession();
		List list = session.createCriteria(this.type)
		.add(Restrictions.eq("entityId", entityId))
		.add(Restrictions.eq("name", name)).list();
		if(list!=null && list.size()!=0)
		    return (Variable) list.get(0);
		else 
			return null;
	}

	

	@Override
	public void setVariable(Variable variable)
			throws DataAccessException {
		Variable var = get(variable.getEntityId(),variable.getName());
		if(var!=null){
		    var.setValue(variable.getValue());
		    var.setDateTime(variable.getDateTime());
		    update(var);
		}else
			create(variable);

	}

	@Override
	public void create(Long entityId, String name, String value)
			throws DataAccessException {
		Variable variable = new Variable(entityId,name,value);
		saveOrUpdate(variable);
		
	}

	@Override
	public void create(Long entityId, String name,
			DateTime value) throws DataAccessException {
		Variable variable = new Variable(entityId,name,value);
		saveOrUpdate(variable);
		
	}

	@Override
	public void setVariable(Long entityId, String name, String value)
			throws DataAccessException {
		Variable var = get(entityId,name);
		if(var!=null){
		    var.setValue(value);		       
		    update(var);
		    
		}else{
			var =  new Variable(entityId,name,value);
			var.setName(name);
			var.setEntityId(entityId);
			var.setValue(value);
			create(var);
		}
	}

	@Override
	public void setVariable(Long entityId, String name, DateTime value)
			throws DataAccessException {
		Variable var = get(entityId,name);
		if(var!=null){
		    var.setDateTime(value);		   	    
		    update(var);
		}else{
			var =  new Variable(entityId,name,value);
			var.setName(name);
			var.setEntityId(entityId);
			var.setDateTime(value);
			create(var);
		}
		
	}

}
